<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/10
 * Time: 12:01
 */

namespace plugin\admin\app\logic\image;


use app\common\lib\Common;
use plugin\admin\app\exception\AdminException;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\image\ImageModelModel;
use plugin\admin\app\model\queue\AiImageRequestQueueModel;
use support\Request;
use support\Response;

class TestLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {

    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function regenerateImage(Request $request): Response
    {
        if(empty($request->input('modelids'))){
            throw new AdminException(4020,'模型风格必选');
        }
        if(empty($request->input('prompt'))){
            throw new AdminException(4020,'英文描述词不能为空');
        }
        if(empty($request->input('ai_image_command'))){
            throw new AdminException(4020,'生成图像指令不能为空');
        }
        $prompt          = $request->input('prompt');
        $aiImageCommand  = $request->input('ai_image_command');
        $aiImageCommands = json_decode($aiImageCommand, true);
        if ($aiImageCommands == false) {
            throw new AdminException(4020, '图像指令JSON格式错误');
        }

        if(empty($request->input('steps'))){
            throw new AdminException(4020,'步长不能为空');
        }
        if(empty($request->input('samplers'))){
            throw new AdminException(4020,'采样器不能为空');
        }
        $steps = array_values(array_filter(explode("\n", $request->input('steps'))));

        $samplers = array_values(array_filter(explode("\n", $request->input('samplers'))));

        $modelids = $request->input('modelids');
        $models = ImageModelModel::getInstance()->getWhere(['status'=>1,'isdel'=>0,['id','in',$modelids]])->orderBy('id','desc')->get();

        $data = [];
        $requestIds = [];
        foreach ($models as $model) {
            foreach ($samplers as $sampler) {
                foreach ($steps as $step) {
                    $aiImageCommands['steps'] = (int)$step;
                    $aiImageCommands['sampler_name'] = $sampler;
                    $aiImageCommands['sampler_index'] = $sampler;
                    $aiImageCommand = json_encode($aiImageCommands);
                    $requestId = Common::generatedAIImageByTemplate($aiImageCommand, $prompt, $model['model'], ['batch_size' => 1], 'admin_batch_image_test');
                    $data[$model['name']][$sampler][] = ['step'=>$step,'requestid'=>$requestId??''];
                    $requestIds[] = $requestId??'';
                }
            }
        }

        $returnData = [];
        foreach ($data as $model=>$val){
            foreach($val as $sampler=>$v){
                $returnData[] = ['model'=>$model,'sampler'=>$sampler,'list'=>$v];
            }
        }

        return $this->json(0,'ok',['data'=>$returnData,'requestids'=>$requestIds]);
    }

    public function getAiImageResult(Request $request): Response
    {
        set_time_limit(0);
        $requestId = $request->input('requestid');
        if($requestId==false){
            throw new AdminException(4020,'请求Id不存在');
        }

        while (true){
            $images = Common::getAiImageResult($requestId);
            if($images){
                $first = (new AiImageRequestQueueModel())->getWhere(['requestid'=>$requestId])->first();
                return json(['code' => 0, 'data' => ['images'=>$images,'tts'=>$first['tts'],'requestid'=>$requestId], 'msg' => 'ok']);
            }

            sleep(3);
            $first = (new AiImageRequestQueueModel())->getWhere(['requestid'=>$requestId])->first();
            if($first && !empty($first['start_time']) && (time()-strtotime($first['start_time']))>300){
                //如果是批量生成的，跳过，检查下一个
                throw new IndexException(4020,'生成超时');
            }elseif ($first==false){
                throw new IndexException(4020,'加入队列失败');
            }
        }
    }

    public function update(Request $request): Response
    {
        file_put_contents(runtime_path('admin_image_test_param'),json_encode($request->all(),256));

        return $this->json(0,'ok',[1]);
    }
}